﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;


namespace iPublic
{
    /// <summary>
    /// 从微信官方例子中改造过来的log，用于记录系统日志到文件。
    /// 修改记录：
    ///   20170629，zch
    /// </summary>
    public partial class iLog
    {
        public static int LOG_LEVEL = 3;
        //在网站根目录下创建日志目录
        public static string path = ""; //HttpContext.Current.Request.PhysicalApplicationPath + "log";
        

        /**
         * 向日志文件写入调试信息
         * @param className 类名
         * @param content 写入内容
         */
        public static void Debug(string className, string content)
        {
            if (LOG_LEVEL >= 3)
            {
                WriteLog("DEBUG", className, content);
            }
        }

        /**
        * 向日志文件写入运行时信息
        * @param className 类名
        * @param content 写入内容
        */
        public static void Info(string className, string content)
        {
            if (LOG_LEVEL >= 2)
            {
                WriteLog("INFO", className, content);
            }
        }

        /**
        * 向日志文件写入出错信息
        * @param className 类名
        * @param content 写入内容
        */
        public static void Error(string className, string content)
        {
            if (LOG_LEVEL >= 1)
            {
                WriteLog("ERROR", className, content);
            }
        }


        public static FileInfo fileInfo = null;
        public static FileStream fileStream = null;
        public static StreamWriter fileWriter = null;
        /**
        * 实际的写日志操作
        * @param type 日志记录类型
        * @param className 类名
        * @param content 写入内容
        */
        public static void WriteLog(string type, string className, string content)
        {
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");//获取当前系统时间
            string filename = "";
            //StreamWriter fileWriter = null;
            try
            {
                if (string.IsNullOrEmpty(path)) path = checkDefaultPath();
                //创建或打开日志文件，向日志文件末尾追加记录。fileWriter.Close之后其baseStream就是null了但是fileWriter不是null
                if (fileWriter == null || fileWriter.BaseStream==null)
                {
                    filename = path + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";//用日期对日志文件命名
                    if (fileWriter != null) fileWriter.Dispose();   //释放
                    fileWriter = File.AppendText(filename);
                }

                //向日志文件写入内容
                string write_content = time + " " + type + " " + className + ": " + content;
                fileWriter.WriteLine(write_content);

                //关闭日志文件
                fileWriter.Close();
            }
            catch (Exception x)
            { }
        }


        #region //writeLogFile，写日志
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <param name="info"></param>
        public static void writeLogFile(string info, bool lTime=true)
        {
            string fileName = "";
            try
            {
                if (fileInfo == null)
                {
                    if (string.IsNullOrEmpty(path)) path = checkDefaultPath();
                    // 初始化日志txt
                    fileName = path + DateTime.Now.ToString("yyyyMMdd-HHmm") + ".txt";
                    if (!File.Exists(fileName)) File.CreateText(fileName).Close();  //创建后立刻释放
                    fileInfo = new FileInfo(fileName);
                }
                //创建只写文件流
                //当fileWriter.Close后fileStream也基本上释放了，需要重建
                if (fileStream == null || !fileStream.CanWrite)
                {
                    if (fileStream != null) fileStream.Dispose();
                    fileStream = fileInfo.OpenWrite();
                }

                // 根据上面创建的文件流创建写数据流
                //using (FileStream fs = logFileStream) { }
                //当fileWriter.Close后fileWriter.BaseStream就是null了，但是fileWriter自身不是null
                if (fileWriter == null || fileWriter.BaseStream == null)
                {
                    if (fileWriter != null) fileWriter.Dispose();   //释放
                    fileWriter = new StreamWriter(fileStream);      //fileWriter = File.AppendText(fileName);
                }

                //写入
                StreamWriter w = fileWriter;
                //// 设置写数据流的起始位置为文件流的末尾 
                w.BaseStream.Seek(0, SeekOrigin.End);
                if (lTime) info = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " " + info;
                w.WriteLine(info);              //w.Write(info);
                // 清空缓冲区内容，并把缓冲区内容写入基础流 
                w.Flush();
                // 关闭写数据流，关闭后w.BaseStream就是null了但是w并不是null
                //w.Close();                    //是不是需要关闭，这是个问题，经试验，不关闭直接关了程序，也不会有影响
            }
            catch (Exception x)
            {
                //showInfo(x.Message, true, false);
            }
        }
        #endregion


        private static string checkDefaultPath()
        {
            string s = Path.GetDirectoryName(iDefine.findSysDirectory());
            if (string.IsNullOrEmpty(s))
            {
                //if (HttpContext.Current != null)
                //    s = HttpContext.Current.Server.MapPath("~/");   //HttpContext.Current.Request.PhysicalApplicationPath
                //else
                    s = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath); //System.Environment.CurrentDirectory;
            }
            s += "\\系统日志\\";
            if (!Directory.Exists(s)) Directory.CreateDirectory(s);
            return s;
        }

    }

}
